//
//  BNDofficeDocSignedVc.m
//  OfficeDoc
//
//  Created by pie on 2022/4/5.
//  Copyright © 2022 pie. All rights reserved.
//

#import "BNDofficeDocSignedVc.h"
#import "BNDOfficeDocSignedSwitch.h"
//#import "UINavigationController+FDFullscreenPopGesture.h"
//#import "UIViewController+RTRootNavigationController.h"
#import "BNDPushVCHandler.h"
#import <AliyunOSSiOS/AliyunOSSiOS.h>

@interface BNOfficeDocSignView : UIView
{
    CGPoint points[5];
}
@property(nonatomic,assign) NSInteger control;
@property(nonatomic,strong) UIBezierPath *beizerPath;
@property (assign) BOOL isSigned;           //是否已经签名

@property(nonatomic,strong)  VoidBlock block;
- (UIImage *)getSignatureImage;
- (void)clearSignature;

@end

@implementation BNOfficeDocSignView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.beizerPath = [UIBezierPath bezierPath];
        [self.beizerPath setLineWidth:4];
        self.backgroundColor = UIColor.clearColor;
        _isSigned = NO;
    }
    return self;
}

#pragma mark - 绘图操作
- (void)drawRect:(CGRect)rect{
    //设置签名的颜色
    UIColor *strokeColor = [UIColor blackColor];
    [strokeColor setStroke];
    //签名的路径绘制
    [self.beizerPath stroke];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.control = 0;
    UITouch *touch = [touches anyObject];
    points[0] = [touch locationInView:self];
    CGPoint startPoint = points[0];
    CGPoint endPoint = CGPointMake(startPoint.x + 1.5, startPoint.y + 2);
    [self.beizerPath moveToPoint:startPoint];
    [self.beizerPath addLineToPoint:endPoint];
    BND_BLOCK_EXEC(self.block);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    _isSigned = YES;
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    _control++;
    points[_control] = touchPoint;
    
    if (_control == 4){
        points[3] = CGPointMake((points[2].x + points[4].x)/2.0, (points[2].y + points[4].y)/2.0);
        
        //设置画笔起始点
        [self.beizerPath moveToPoint:points[0]];
        
        //endPoint终点 controlPoint1、controlPoint2控制点
        [self.beizerPath addCurveToPoint:points[3] controlPoint1:points[1] controlPoint2:points[2]];
        
        //setNeedsDisplay会自动调用drawRect方法，这样可以拿到UIGraphicsGetCurrentContext，就可以画画了
        [self setNeedsDisplay];
        
        points[0] = points[3];
        points[1] = points[4];
        _control = 1;
    }
}

#pragma mark - 清除签名
- (void)clearSignature{
    [self.beizerPath removeAllPoints];
    [self setNeedsDisplay];
    _isSigned = NO;
}

#pragma mark - 获取图片
- (UIImage *)getSignatureImage {
    if(!_isSigned){
        return nil;
    }
    //设置为NO，UIView是透明这里的图片就是透明的
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *signatureImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSString* docDir = [NSString stringWithFormat:@"%@/Documents/Image", NSHomeDirectory()];
    [[NSFileManager defaultManager] createDirectoryAtPath:docDir withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *path = [NSString stringWithFormat:@"%@/Documents/Image/IMAGE.PNG", NSHomeDirectory()];
    
    //用png是透明的
    [UIImagePNGRepresentation(signatureImage) writeToFile: path atomically:YES];
    return signatureImage;
}

@end


@interface BNDofficeDocSignedVc ()<UIGestureRecognizerDelegate>
{
    BnsignString  comp;
    Bnsignvoid  cancel;
}
@property (strong, nonatomic) UILabel *tipLabel;
@property (strong, nonatomic) BNOfficeDocSignView *signView;
@property (strong, nonatomic) BNDOfficeDocSignedSwitch *signedSwitch;

@property (copy, nonatomic) NSString *officeDocId;
@end

@implementation BNDofficeDocSignedVc

+(void)bnd_sign:(UIViewController *)top title:(NSString *)title officeDocId:(NSString * _Nullable )officeDocId comp:(BnsignString)comp cancel:(Bnsignvoid)cancel
{
    BNDofficeDocSignedVc * sign = BNDofficeDocSignedVc.new;
    sign.officeDocId = officeDocId;
    sign.title = title;
    sign->comp = comp;
    sign->cancel = cancel;
    [[BNDPushVCHandler currentSelectedNavController] pushViewController:sign animated:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer
                                      *)gestureRecognizer
{
    return NO; //YES：允许右滑返回 NO：禁止右滑返回
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //    self.rt_disableInteractivePop = YES;
    //    self.fd_interactivePopDisabled = YES;
    
    UIButton * restBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [restBtn setTitle:@"清除" forState:0];
    [restBtn lk_setTextColor:UIColorWithHex(0xF85757)];
    [restBtn lk_setFont:BNDPFMediumFont(16)];
    [self.view addSubview:restBtn];
    
    UIButton * sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [sureBtn setTitle:@"确认" forState:0];
    [sureBtn lk_setTextColor:UIColorWithHex(0x3770EB)];
    [sureBtn lk_setFont:BNDPFMediumFont(16)];
    [self.view addSubview:sureBtn];
    [restBtn addTarget:self action:@selector(restAction) forControlEvents:UIControlEventTouchUpInside];
    [sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat bb_w = 44;
    CGFloat bb_h = 44;
    restBtn.frame = CGRectMake(16, kDeviceHeight-44-BNDSafeAreaBottomHeight()-10, bb_w, bb_h);
    sureBtn.frame = CGRectMake(kDeviceWidth-44-16, restBtn.frame.origin.y, bb_w, bb_h);
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, BNDNavigationBarHeight(), kDeviceWidth, kDeviceHeight-BNDNavigationBarHeight()-25-44-BNDSafeAreaBottomHeight())];
    bottomView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bottomView];
    
    _tipLabel = ({
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = BNDPFMediumFont(16);
        titleLabel.textColor = UIColorWithHex(0x959BA6);
        titleLabel.text = @"请在此处手写您的签名";
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.numberOfLines = 1;
        titleLabel;
    });
    [self.view addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(bottomView);
    }];
    
    _signView = BNOfficeDocSignView.new;
    [self.view addSubview:_signView];
    @weakify(self)
    [_signView setBlock:^{
        @strongify(self)
        self.tipLabel.hidden = YES;
    }];
    [_signView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(bottomView);
        make.size.mas_equalTo(CGSizeMake(kDeviceWidth, kDeviceWidth*74.0/210.0));
    }];
    
    
    _signedSwitch = [[BNDOfficeDocSignedSwitch alloc] init];
    [_signedSwitch setBlcok:^(id _Nullable data) {
        @strongify(self)
        [self restAction];
        NSString *lineWited = data;
        if(lineWited.intValue ==0){
            [self.signView.beizerPath setLineWidth:4];
        }else{
            [self.signView.beizerPath setLineWidth:8];
        }
    }];
    [self.view addSubview:_signedSwitch];
    [_signedSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bottomView);
        make.centerY.mas_equalTo(restBtn);
        make.size.mas_equalTo(CGSizeMake(160, 40));
    }];
    
}

// 重置
-(void)restAction
{
    [_signView clearSignature];
    self.tipLabel.hidden = NO;
}

//确定
-(void)sureAction
{
    UIImage * img = [_signView getSignatureImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5f);
    [self onOssButtonNormalPut:data];
    
    
}

// 普通上传
- (void)onOssButtonNormalPut:(NSData *)data
{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    NSString *objectKey = [NSString stringWithFormat:@"dev/officedoc/%@.png",[self getNowTimeTimestamp]];
    // 填写Bucket名称，例如examplebucket。
    put.bucketName = @"bnd-clouddisk";
    // 填写Object完整路径。Object完整路径中不能包含Bucket名称，例如exampledir/testdir/exampleobject.txt。
    put.objectKey = objectKey;
    // 直接上传NSData。
    put.uploadingData = data;
    NSMutableDictionary *meta = [NSMutableDictionary dictionary];
    [meta setObject:@"public-read" forKey:@"x-oss-object-acl"];
    put.objectMeta = meta;
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalByteSent);
        CGFloat  progressData  = ((float)bytesSent/totalByteSent);
        if (progressData > 0) {
            BND_dispatch_main_async_safe(^{
                [ReminderHUD showProgress:progressData status:@"上传中"];
            })
        }
        
    };
    @weakify(self)
    OSSTask * putTask = [[BNDPreference sharedInstance].client putObject:put];
    if(putTask == nil){
        [BNDPreference hanOSSUploadFile];
        [ReminderHUD showReminderText:@"请重新提交" delayTime:1];
        return;
    }
    [putTask continueWithBlock:^id(OSSTask *task) {
        @strongify(self)
        if (!task.error) {
//            NSString *imageUrl = [[BNDPreference sharedInstance] handleProduceImageUrl:put.objectKey];
//            NSLog(@"--OSS成功了---%@",imageUrl);
            OSSTask *task = [[BNDPreference sharedInstance].client presignPublicURLWithBucketName:@"bnd-clouddisk" withObjectKey:put.objectKey];
            [self handleUploadImageUrl:task.result];
            
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
}

- (void)handleUploadImageUrl:(NSString*)objectKey
{
    @weakify(self)
    [BNDApiManager officeDocAnnouncementSign:self.officeDocId signaturePic:objectKey success:^{
        @strongify(self)
        [ReminderHUD disappear];
        [ReminderHUD showReminderText:@"上传成功" delayTime:1];
        BND_BLOCK_EXEC(self->comp,objectKey);
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError * _Nullable error) {
        [ReminderHUD disappear];
        [ReminderHUD showReminderText:@"上传失败" delayTime:1];
    }];
}


- (NSString *)getNowTimeTimestamp
{//毫秒级
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
    
}

@end
